package user;

import utils.JsonOut;
import utils.MysqlUtils;
import utils.VerifyEmail;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet(name = "RegServlet")
public class RegServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String email = request.getParameter("email");
        String nickname = request.getParameter("nickname");
        String psw = request.getParameter("password");
        String verify = request.getParameter("verify");

        HttpSession session = request.getSession();
        Object captchaAttr = session.getAttribute("validation_code");


        PrintWriter out = response.getWriter();
        if (captchaAttr == null){
            out.println(JsonOut.error(201, "captcha_empty"));
            return;
        }
        if (email == null || email.isEmpty()){
            out.println(JsonOut.error(201, "email_empty"));
            return;
        }
        if (nickname == null || nickname.isEmpty()){
            out.println(JsonOut.error(201, "nickname_empty"));
            return;
        }
        if (psw == null || psw.isEmpty()){
            out.println(JsonOut.error(201, "psw_empty"));
            return;
        }
        if (verify == null || verify.isEmpty()){
            out.println(JsonOut.error(201, "verify_empty"));
            return;
        }

        String captcha = captchaAttr.toString();
        // 忽略大小写
        verify = verify.toLowerCase();
        captcha = captcha.toLowerCase();
        if (!verify.equals(captcha)){
            out.println(JsonOut.error(103, "verify"));
            return;
        }

        String savedPass = (new MysqlUtils()).getPassword(email);
        if (savedPass != null){
            out.println(JsonOut.error(111, "email_exist"));
            return;
        }

        Pattern pattern = Pattern.compile("([\u4e00-\u9fa5]|[a-z]|[A-Z]|[0-9]|-|_)+");
        Matcher nameValid = pattern.matcher(nickname);
        if (!nameValid.matches()){
            out.println(JsonOut.error(201, "bad_nickname"));
            return;
        }

        if ((new MysqlUtils()).isUsernameExist(nickname)){
            out.println(JsonOut.error(113, "nickname_exist"));
            return;
        }



        if (psw.length() < 6){
            out.println(JsonOut.error(112, "psw_too_short"));
            return;
        }

        String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 32; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }

        String emailError = "";
        if ((new MysqlUtils()).userRegister(email, nickname, psw, sb.toString())){
            if(!VerifyEmail.send(email, "reg", sb.toString())) emailError = "_but_email_error";
            session.setAttribute("login_user_email", email);
            out.println(JsonOut.error(0, "reg_success"+emailError));
        }
        else
            out.println(JsonOut.error(500, "reg_failed"));
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println(JsonOut.error(403, "forbidden"));
    }
}
